package source

import (
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"

	"google.golang.org/appengine"
	"google.golang.org/appengine/urlfetch"
)

//Jianshu 获得简书网的一篇文章内容
func Jianshu(urlStr string, req *http.Request) string {
	c := appengine.NewContext(req) //gae不允许defaultClient&defaultTransport
	client := urlfetch.Client(c)   //此处client不需要Jar
	req, err := http.NewRequest("GET", urlStr, nil)
	CheckErr(err)
	res, err := client.Do(req)
	CheckErr(err)
	defer res.Body.Close()
	output, err := ioutil.ReadAll(res.Body)
	CheckErr(err)
	r := regexp.MustCompile(`title" target="_blank" href="/p/(\w{12})">`)
	urls := r.FindString(string(output))
	urls = strings.Replace(urls, `title" target="_blank" href="`, "http://www.jianshu.com", 1)
	urls = strings.Replace(urls, `">`, "", 1) // 获得文章地址

	req, err = http.NewRequest("GET", urls, nil)
	CheckErr(err)
	res, err = client.Do(req)
	CheckErr(err)
	defer res.Body.Close()
	output, err = ioutil.ReadAll(res.Body) //获得文章内容
	CheckErr(err)
	//第一个(.*?)是标题，第二个是内容
	r = regexp.MustCompile(`(?s)<h1 class="title">(.*?)</h1>.*?<div class="show-content">(.*?)<div class="visitor_edit">`)
	msgs := r.FindAllStringSubmatch(string(output), -1)

	if len(msgs) != 0 {
		r := regexp.MustCompile(`(?s)<div class="image-package">\s<img src="(.*?)\?imageView.*?image-caption">(.*?)</div>\s</div>`)
		msgs[0][2] = r.ReplaceAllString(msgs[0][2], "[align=center][img]${1}[/img][/align]\n[align=center][color=#c0c0c0]${2}[/color][/align]\n")
		msgs[0][2] = strings.Replace(msgs[0][2], "<div>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</div>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<p>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</p>", "\n", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<br>", "\n", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<b>", "[b]", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</b>", "[/b]", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<h1>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</h1>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<h2>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</h2>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<h3>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</h3>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "<h4>", "", -1)
		msgs[0][2] = strings.Replace(msgs[0][2], "</h4>", "", -1)

		msgs[0][2] = strings.TrimSpace(msgs[0][2])
		return "[table=98%,rgb(252, 253, 254)]\n[tr][td][align=center][b][size=5][color=#4169e1]" + msgs[0][1] + "[/color][/size][/b][/align][/td][/tr]\n[/table]\n" + msgs[0][2]
	}
	return ""
}
